package com.victor.utils.weather;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 和风天气
 * 
 * @author zhangbin
 * 
 * @see 使用文档https://dev.heweather.com/docs/api/weather
 * 
 */
public class Hf_weather {

	public static void main(String[] args) {
		getNowWeather("");
	}

	public static String getNowWeather(String city) {
		// 参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode 字符集 UTF-8
		String params = "key=9c43858ac1e14d1abe1b69588eb8850e&location=" + city;
		StringBuilder sb = new StringBuilder();
		InputStream is = null;
		BufferedReader br = null;
		PrintWriter out = null;
		try {
			// 接口地址
			String url = "https://free-api.heweather.net/s6/weather";
			URL uri = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
			connection.setRequestMethod("POST");
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(10000);
			connection.setRequestProperty("accept", "*/*");
			// 发送参数
			connection.setDoOutput(true);
			out = new PrintWriter(connection.getOutputStream());
			out.print(params);
			out.flush();
			// 接收结果
			is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			String line;
			// 缓冲逐行读取
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			System.out.println(sb.toString());
		} catch (Exception ignored) {
		} finally {
			// 关闭流
			try {
				if (is != null) {
					is.close();
				}
				if (br != null) {
					br.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception ignored) {
			}
		}
		return sb.toString();
	}

}
